package cn.edu.ljl.rest;

import cn.edu.ljl.DBMS;
import cn.edu.ljl.Experience;
import cn.edu.ljl.Student;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.List;

public class ExperienceRefer extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String key = request.getParameter("key");

        String sql = "SELECT * FROM `courses` WHERE" + " `course` LIKE '%" + key + "%'" +
                " OR `nam` LIKE '%" + key + "%'";


        System.out.println(sql);

        try {
            List<Experience> experiences = DBMS.getExperience(sql);

            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            try(Writer writer = response.getWriter()) {
                writer.write(this.toJson(experiences));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    private String toJson(List<Experience> experiences) {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("\"experiences\": [");

        for(int i=0; i<experiences.size(); i++) {
            Experience experience = experiences.get(i);
            if (i > 0) sb.append(",");
            sb.append(String.format(
                    "{\"name\": \"%s\",\"course\": \"%s\",\"advice\":" + " \"%s\"}",
                    experience.getName(),experience.getCourse(),experience.getAdvice()
            ));
        }

        sb.append("]");
        sb.append("}");
        System.out.println(sb);
        return sb.toString();
    }
}


